"use client";
import { useState, useEffect, useRef } from "react";
import { Divider, Skeleton, Modal, Avatar } from "antd";
import { noticeGetNoticeList } from "@/apis";
import Image from "next/image";
import Link from "next/link";
import { AxiosError } from "axios";
import "antd/dist/reset.css";
// 引入Swiper相关资源
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay } from "swiper/modules";
import "swiper/css";
import "swiper/css/autoplay";

// 定义公告数据类型
interface Announcement {
  id: number;
  title: string;
  createTime: string;
  content: string;
}

// 定义接口返回的响应模型
interface ResponseModelListNoticeModel {
  success: boolean;
  code: number;
  message: string;
  data: Announcement[];
}

export default function AnnouncementSection() {
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedNotice, setSelectedNotice] = useState<Announcement | null>(
    null
  );
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [userInfo, setUserInfo] = useState<{
    id: number;
    mobile: string;
    token: string;
  } | null>(null);
  const swiperRef = useRef<any>(null);

  // 格式化日期
  const formatDate = (dateString: string) => {
    if (!dateString) return "";
    const date = new Date(dateString);
    return date
      .toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      })
      .replace(/\//g, "-");
  };

  // 打开公告详情
  const showNoticeDetail = (notice: Announcement) => {
    setSelectedNotice(notice);
    setIsModalOpen(true);
  };

  // 监听用户登录状态
  useEffect(() => {
    const loadUserInfo = () => {
      const storedUserInfo = localStorage.getItem("userInfo");
      if (storedUserInfo) {
        try {
          const userData = JSON.parse(storedUserInfo);
          setUserInfo(userData);
        } catch (error) {
          console.error("解析用户信息失败:", error);
          setUserInfo(null);
        }
      } else {
        setUserInfo(null);
      }
    };

    // 初始加载
    loadUserInfo();

    // 监听自定义事件
    const handleUserInfoChange = () => {
      loadUserInfo();
    };

    window.addEventListener("userInfoChanged", handleUserInfoChange);

    return () => {
      window.removeEventListener("userInfoChanged", handleUserInfoChange);
    };
  }, []);

  // 获取公告数据
  useEffect(() => {
    const fetchAnnouncements = async () => {
      try {
        setLoading(true);
        const result = await noticeGetNoticeList({
          baseURL: "/api/proxy",
        });

        if (result instanceof AxiosError) {
          throw new Error("网络请求失败，请稍后重试");
        }
        if ("data" in result) {
          const responseData = result.data as any;
          if (responseData.success && responseData.code === 0) {
            setAnnouncements(responseData.data || []);
            setError(null);
          } else {
            setError(`获取公告失败: ${responseData.message || "未知错误"}`);
            setAnnouncements([]);
          }
        } else {
          throw new Error("接口返回格式异常");
        }
      } catch (err) {
        console.error("获取公告失败:", err);
        setError(
          err instanceof Error ? err.message : "获取公告失败，请稍后重试"
        );
        setAnnouncements([]);
      } finally {
        setLoading(false);
      }
    };
    fetchAnnouncements();
  }, []);

  return (
    <div className="w-full md:w-2/6 md:h-full flex flex-col items-center justify-start p-4 bg-white shadow-md mt-2 md:mt-0">
      <div className="flex flex-col items-center w-full h-[120px] text-sm text-[#929292]">
        {userInfo ? (
          <Avatar
            size={62}
            className="shadow-lg border-4 border-white"
            style={{
              fontSize: "24px",
              fontWeight: "bold",
              color: "white",
              background: "linear-gradient(135deg, #ec4899, #8b5cf6, #4f46e5)",
            }}
          >
            {userInfo.mobile.charAt(0)}
          </Avatar>
        ) : (
          <Image
            src="/images/loginIcon.png"
            alt="登录图标"
            priority
            width={62}
            height={62}
          />
        )}
        <span className="my-2 text-center">传递质量信任，让人民生活更美好</span>
        <span className="text-center text-[#929292]">
          {userInfo ? (
            <>
              欢迎回来，
              <span className="text-blue-600 font-medium m-1">
                {userInfo.mobile.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")}
              </span>
              ！
            </>
          ) : (
            <>
              快来
              <Link
                href="/login"
                className="text-blue-600 cursor-pointer hover:underline m-2"
              >
                登录
              </Link>
              吧！
            </>
          )}
        </span>
      </div>
      <Divider />

      {/* 公告中心区域 - 使用Swiper实现滚动效果 */}
      <div className="flex flex-col justify-start items-start w-full text-[#666]">
        <div className="font-bold text-lg mb-3">公告中心</div>
        {loading ? (
          <div className="w-full space-y-3">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} paragraph={{ rows: 1 }} active />
            ))}
          </div>
        ) : error ? (
          <div className="w-full text-red-500 text-center py-2">{error}</div>
        ) : announcements.length > 0 ? (
          <div className="w-full h-[180px] overflow-hidden">
            <Swiper
              ref={swiperRef}
              direction="vertical"
              slidesPerView={5}
              spaceBetween={1}
              loop={announcements.length > 5}
              autoplay={{
                delay: 5000,
                disableOnInteraction: false,
              }}
              modules={[Autoplay]}
              className="h-full"
            >
              {announcements.map((announcement) => (
                <SwiperSlide key={announcement.id} className="h-auto">
                  <div
                    className="w-full py-1 hover:bg-gray-100 cursor-pointer text-[#2F2F2F] text-sm transition-colors leading-5 group"
                    title={announcement.title}
                    onClick={() => showNoticeDetail(announcement)}
                  >
                    <div className="flex items-start gap-2">
                      <span className="text-blue-500"> ▎</span>
                      <div className="flex flex-row items-baseline justify-between w-full">
                        <div className="group-hover:text-blue-600 h-6 transition-colors truncate whitespace-nowrap overflow-hidden block w-4/5">
                          {announcement.title}
                        </div>
                        <div className="text-xs text-gray-400 w-1/5 flex justify-end">
                          {formatDate(announcement.createTime)}
                        </div>
                      </div>
                    </div>
                  </div>
                </SwiperSlide>
              ))}
            </Swiper>
          </div>
        ) : (
          <div className="w-full text-gray-500 text-center py-4">暂无公告</div>
        )}
      </div>

      {/* 公告详情弹窗 */}
      <Modal
        title={selectedNotice?.title}
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        footer={null}
        width={700}
        destroyOnHidden={true}
      >
        {selectedNotice && (
          <div className="prose max-w-none">
            <div className="text-sm text-gray-500 mb-4">
              发布时间：{formatDate(selectedNotice.createTime)}
            </div>
            <div
              dangerouslySetInnerHTML={{ __html: selectedNotice.content }}
              className="whitespace-pre-line"
            />
          </div>
        )}
      </Modal>
    </div>
  );
}
